package com.basejace.core.handler;

import java.util.TreeSet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.basejace.core.R;
import com.basejace.core.model.LoginUserBean;
import com.jfinal.handler.Handler;

public class AuthHandler extends Handler {
	//不需要登录就可以访问的url
	private TreeSet<String> skipUrl = new TreeSet<String>();
	
	public AuthHandler() {
		skipUrl.add("/");
		skipUrl.add("/login.jsp");
	}

	@Override
	public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
		HttpSession session = request.getSession();
		LoginUserBean user = (LoginUserBean)session.getAttribute(R.Key.LOGIN_USER);
		
		String uri = request.getRequestURI();
		String ddurl = request.getRequestURL().toString();
		String contextPath = request.getContextPath();
		System.out.println("[[[]]]" + uri + "==" + ddurl);
		if (!skipUrl(uri, request.getContextPath()) && user == null) {
//			request.redi
			request.setAttribute("msg", "登录会话失效，请重新登录...");
//				response.sendRedirect(request.getContextPath() + "/login.jsp");
//				response.
			response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
			// response.sendRedirect(url);	// always 302
			response.setHeader("Location", request.getContextPath());
			//response.setHeader("Connection", "close");
			return;
		}
		
		next.handle(target, request, response, isHandled);
	}

	public boolean skipUrl(String uri, String contextPath) {
		if(skipUrl.contains(uri.substring(contextPath.length())))
				return true;
		else 
			return false;
	}
}
